package com.finance.scheduler.job;


import com.finance.framework.lang.Page;
import com.finance.framework.qurtz.RedisRunningStatusAcquirer;
import com.finance.logistics.computer.DataExtractor;
import com.finance.framework.qurtz.TaskDescriptor;
import com.finance.logistics.computer.DataExtractorParam;
import com.finance.scheduler.service.AbstractTask;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 抽取已经拉取的运单信息
 */
@Component
@Data
public class DataExtractJob implements AbstractTask{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DataExtractor dataExtractor;
    @Autowired
    private RedisRunningStatusAcquirer redisRunningStatusAcquirer;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("**********************计算任务调度开始执行*********************");
        List<Page> list = new ArrayList<Page>();
        try {
            for(int i =0 ;i < 5;i++){
                Page page = this.redisRunningStatusAcquirer.acquirePage(context.getTrigger().getKey());
                list.add(page);
            }
            compute(list);
        } catch (Exception e) {
            this.logger.error(e.getMessage(),e);
        }finally {
            for(Page page : list){
                if(page != null) {
                    this.getRedisRunningStatusAcquirer().putback(context.getTrigger().getKey(), page);
                }
            }
        }
        logger.info("**********************计算任务调度结束执行*********************");
     }

    private void compute(List<Page> pages) throws Exception{
        if(CollectionUtils.isEmpty(pages)){
            DataExtractorParam dataExtractorParam = new DataExtractorParam.Builder().signDate(new Date()).build();
            this.dataExtractor.extract2compute(dataExtractorParam);
        }else{
            for(Page page : pages){
                if(page != null){
                    DataExtractorParam dataExtractorParam = new DataExtractorParam.Builder().signDate(new Date()).page(page).build();
                    this.dataExtractor.extract2compute(dataExtractorParam);
                }
            }
        }
    }

    @Override
    public TaskDescriptor descriptor() {
        return new TaskDescriptor("正常解析数据转计算","default","extractOkData_trigger","extractOkData_trigger","0 0 0 2 * ?",this.getClass().getCanonicalName(),"处理已经ok的运单数据，计算配费");
    }

}
